package com.liu.controller;

import com.liu.domain.dm;
import com.liu.domain.student;
import com.liu.domain.teacher;
import com.liu.repository.DmRepository;
import com.liu.repository.StuRepository;
import com.liu.repository.TeacherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * Created by liu on 17-10-22.
 */
@Controller
public class LoginController {

    @Autowired
    private StuRepository stuRepository;
    @Autowired
    private TeacherRepository teacherRepository;
    @Autowired
    private DmRepository dmRepository;


    @PostMapping("/login")
    public String login(String userName, String password, String role, HttpSession session) {
        if ("stu".equals(role)) {
            student student = stuRepository.login(userName, password);
            student student1 = stuRepository.login1(userName, password);
            if (student != null) {
                session.setAttribute("user", student);
                return "redirect:/student";
            } else if (student1 != null){
                session.setAttribute("user", student1);
                return "redirect:/student";
            }
        } else if ("admin".equals(role)) {
            teacher teacher = teacherRepository.login(userName,password);
            if (teacher !=null){
                session.setAttribute("user",teacher);
                System.out.print(session.toString());
                return "redirect:/we";
            }

        } else if ("xitong".equals(role)){

            int i;
            i=Integer.valueOf(userName).intValue();
            dm dm = dmRepository.login(i,password);
            if (dm != null){
                session.setAttribute("user",dm);
                return "redirect:/xtindex";
            }
        }

        return "redirect:/login?w=1";
       /* ModelAndView mav = new ModelAndView();
        mav.setViewName("Addtext");
        mav.addObject("cw", 1);
        return mav;*/
    }

    @RequestMapping("/loginout")
    public String loginOut(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }
}
